<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="名称">
              <a-auto-complete v-model:value="writeOffWhere.customer" :options="customerOptions2" placeholder="请输入名称"
                @select="customer_onSelect2" @search="customer_onSearch2" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="对账日期">
              <a-date-picker v-model:value="writeOffWhere.writeDate" valueFormat="YYYY-MM" format="YYYY-MM" picker="month"
                placeholder="请输入对账日期" class="ele-fluid" :allow-clear="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="选择">
              <a-select v-model:value="writeOffWhere.state" placeholder="请输入状态" allow-clear>
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="未收款">未收款</a-select-option>
                <a-select-option value="已收款">已收款</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="writeOffReload">查询</a-button>
                <a-button @click="writeOffReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="writeOffTableRef" row-key="id" :columns="columns" :datasource="datasource"
        @update:selection="writeOffTableOnSelectionChange" :customRow="writeOffTableRowClick"
        v-model:current="writeOffCurrent" cacheKey="writeOff" :scroll="{ x: 1000 }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="writeOffOpenEdit()" v-any-permission="['order:writeOff:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
            <a-popconfirm v-any-permission="['order:writeOff:update']" :title="(writeOffCurrent.customer??'')+ (writeOffCurrent.writeDate??'')+'' + '收款确认吗？'"
              v-if="writeOffCurrent.id" @confirm="receiveComfirm()">
              <a-button type="primary" v-any-permission="['order:writeOff:update']">
                <template #icon>
                  <plus-outlined />
                </template>
                <span>收款</span>
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space v-if="record.state !== '已收款'">
              <a  @click="writeOffOpenEdit(record)" v-any-permission="['order:writeOff:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="writeOffRemove(record)">
                <a class="ele-text-danger" v-any-permission="['order:writeOff:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 对账管理添加、修改弹窗 -->
    <ele-modal :width="460" v-model:visible="writeOffVisible_modal" :confirm-loading="loading"
      :title="writeOffIsUpdate ? '修改对账管理' : '新建对账管理'" position="center" :body-style="{ paddingBottom: '8px' }"
      @ok="writeOffSave" :maskClosable="false">
      <a-form ref="writeOffFormRef" :model="writeOffForm" :rules="writeOffRules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-form-item label="客户" name="customer">
          <a-auto-complete v-model:value="writeOffForm.customer_val" :options="customerOptions" placeholder="请输入客户名称"
            @select="customer_onSelect" @search="customer_onSearch" @blur="customer_blur" allow-clear />
        </a-form-item>
        <a-form-item label="对账日期" name="writeDate">
          <a-date-picker v-model:value="writeOffForm.writeDate" valueFormat="YYYY-MM" format="YYYY-MM" picker="month"
            placeholder="请输入对账日期" class="ele-fluid" :allow-clear="false" />
        </a-form-item>
        <a-form-item label="对账金额" name="writePrice">
          <!-- <a-input-number v-model:value="writeOffForm.writePrice" prefix="￥" autocomplete="off" allow-clear
            placeholder="请输入对账金额" class="ele-fluid" /> -->
          <a-input allow-clear :maxlength="200" placeholder="请输入对账金额" v-model:value="writeOffForm.writePrice"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="开票金额" name="invoicePrice">
          <!-- <a-input-number v-model:value="writeOffForm.invoicePrice" prefix="￥" autocomplete="off" allow-clear
            placeholder="请输入开票金额" class="ele-fluid" /> -->
          <a-input allow-clear :maxlength="200" placeholder="请输入开票金额" v-model:value="writeOffForm.invoicePrice"
            autocomplete="off" />
        </a-form-item>
        <a-form-item label="拖车订单" name="billIds">
          <!-- v-model:modelValue="writeOffForm.billIds" 目前没有用 -->
          <advanced ref="advancedComp" @dataBillids="dataBillids" v-model:modelValue="writeOffForm.billIds"></advanced>
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="writeOffForm.remark" allow-clear :maxlength="1200" placeholder="请输入备注"
            autocomplete="off" :rows="4" />
        </a-form-item>
        <a-form-item label="财务备注" name="financeRemark">
          <a-textarea v-model:value="writeOffForm.financeRemark" allow-clear :maxlength="1200" placeholder="请输入财务备注"
            autocomplete="off" :rows="4" />
        </a-form-item>
        <!-- <a-form-item label="状态" name="state">
          <a-select v-model:value="writeOffForm.state" placeholder="请输入状态" allow-clear>
            <a-select-option value="未收款">未收款</a-select-option>
            <a-select-option value="已收款">已收款</a-select-option>
          </a-select>
        </a-form-item> -->
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';

import dayjs from 'dayjs'

import { listCustomersSel } from '@/api/order/customer';
import { pageWriteOff, removeWriteOff, addWriteOff, updateWriteOff,receiveState } from '@/api/order/writeOff';


import advanced from './components/advanced.vue';

const advancedComp = ref(null)
// 表格实例
const writeOffTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (writeOffTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '客户',
    dataIndex: 'customer',
    key: 'customer',
    // sorter: true
  },
  {
    title: '对账日期',
    dataIndex: 'writeDate',
    key: 'writeDate',
    // sorter: true
  },
  {
    title: '对账金额',
    dataIndex: 'writePrice',
    key: 'writePrice',
    // sorter: true
  },
  {
    title: '开票金额',
    dataIndex: 'invoicePrice',
    key: 'invoicePrice',
    // sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    // sorter: true
  },
  {
    title: '财务备注',
    dataIndex: 'financeRemark',
    key: 'financeRemark',
    // sorter: true
  },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    // sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: writeOffWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  return pageWriteOff({ ...where, ...orders, page, limit });
};

/* 搜索 */
const writeOffReload = () => {
  writeOffTableRef?.value?.reload({ page: 1, where: writeOffWhere });
};
const writeOffReload2 = () => {
  writeOffTableRef?.value?.reload();
};

let writeOffWhere_timeout = 0
watch(() => writeOffWhere, (val) => {
  clearTimeout(writeOffWhere_timeout)
  writeOffWhere_timeout = setTimeout(() => {
    writeOffReload();
  }, TIME_OUT);
},
  { deep: true }
)

/*  重置 */
const writeOffReset = () => {``
  resetFields();
  writeOffReload();
};

/* 删除单个 */
const writeOffRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeWriteOff(record.id).then((msg) => {
    hide();
    message.success(msg);
    writeOffReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};

// 当前选中数据
const writeOffCurrent = ref({customer: '', writeDate: ''});

// 弹窗是否打开
const writeOffVisible_modal = ref(false);

// 是否是修改
const writeOffIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const writeOffFormRef = ref(null);

// 表单数据
const { form: writeOffForm, resetFields: writeOffResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
  writeDate: dayjs().subtract(1, 'day').format('YYYY-MM'),
  state: '未收款'
});

// 表单验证规则
const writeOffRules = reactive({
  customer: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
  writePrice: [
    {
      required: false,
      pattern: '^[\-?|0-9]{1,}(\.[0-9]{1,2})?$',
      message: '请输入金额',
    }
  ],
  invoicePrice: [
    {
      required: false,
      pattern: '^[\-?|0-9]{1,}(\.[0-9]{1,2})?$',
      message: '请输入金额',
    }
  ],
  billIds: [
    {
      required: true,
      message: '请选择拖车订单',
      type: 'string',
    }
  ],
});
// document.addEventListener('mouseup' ,function () {
//   // advanced writeOffForm
// });

//防止重复刷新
//客户下拉列表
const customerOptions = ref([]);
let customer_m_timeout = 0
const customer_onSearch = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '货代', keywords: 'salesman' }).then(msg => {
      customerOptions.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
customer_onSearch()
const customer_onSelect = (value2, option2) => {
  writeOffForm.customer_val = option2.label
  writeOffForm.customer = option2.label
  writeOffForm.customerId = option2.value
};
const customer_blur = () => {
  writeOffForm.customer_val = writeOffForm.customer
};
const customerOptions2 = ref([]);
const customer_onSearch2 = searchText => {
  clearTimeout(customer_m_timeout)
  customer_m_timeout = setTimeout(() => {
    listCustomersSel({ 'name': searchText, type: '货代' }).then(msg => {
      customerOptions2.value = msg
    }).catch((e) => {
    })
  }, TIME_OUT);
};
//搜索客户条件
const customer_onSelect2 = (value2, option2) => {
  writeOffWhere.customer = option2.label
};


let writeOffTableRowClick = (record, index) => {
  return {
    onClick: (event) => {
      writeOffCurrent.value = record
    },
  }
}
let writeOffTableOnSelectionChange = (current_options) => {
  writeOffCurrent.value = current_options[0];
};

//收款 方法
const receiveComfirm = () => {
  writeOffCurrent.value.state='已收款'
  receiveState(writeOffCurrent.value).then((msg) => {
    message.success('收款成功');
    writeOffReload2()
  }).catch((e) => {
    message.error(e.message);
  });
  // finishState({ids: writeOffCurrent.value.billIds}).then((msg) => {
  //   message.success('结单成功');
  //   writeOffReload2()
  // }).catch((e) => {
  //   message.error(e.message);
  // });
}
/* 打开编辑弹窗 */
const writeOffOpenEdit = async (record) => {
  writeOffResetFormFields();
  writeOffFormRef.value?.clearValidate();
  writeOffCurrent.value = record ?? {};
  writeOffVisible_modal.value = true;
  Object.assign(writeOffForm, record ?? {});
  writeOffForm.customer_val = record?.customer ?? ''
  writeOffIsUpdate.value = !!record;
  await nextTick()
  //nextTick 子组件还没有初始化  必须使用nextTick 不然调用不到方法
  advancedComp.value?.setInitValue2(writeOffForm.billIds)
};

// document.addEventListener('mouseup' ,function () {
//     console.log(billIds_m.value, writeOffForm.billIds, JSON.parse(writeOffForm.billIds??'[]'));
// });
function dataBillids(data) {
  writeOffForm.billIds = JSON.stringify(data)
}
 
/* 保存编辑 */
const writeOffSave = () => {
  if (!writeOffFormRef.value) {
    return;
  }
  writeOffFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = writeOffIsUpdate.value ? updateWriteOff : addWriteOff;
    saveOrUpdate(writeOffForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      writeOffVisible_modal.value = false;
      writeOffReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};
</script>

<script>
export default {
  name: 'DemoTest'
};
</script>

